import type { DropdownItemOption } from 'vant/lib/dropdown-item/types';
import type { SetDeckQueryParams, SearchSettingList } from '/@/api/deckSet/model/setDeckModel';
import type { UnwrapNestedRefs } from 'vue';
import { SearchSettingTypeEnum } from '/@/api/currentDeck/model/deckModel';
import { defineComponent } from 'vue';
import { find, includes } from 'lodash-es';

import('./ListFilterBox.less');

export default defineComponent({
  name: 'ListFilterBox',
  props: {
    attrKey: {
      type: String as PropType<string>,
      required: true,
    },
    queryState: {
      type: Object as PropType<UnwrapNestedRefs<SetDeckQueryParams>>,
      required: true,
    },
    searchConfigData: {
      type: Object as PropType<SearchSettingList>,
      required: true,
    },
  },
  emits: ['pageRefresh'],
  setup(props, { emit }) {
    const multipleClick = (item: DropdownItemOption, key: string) => {
      const { queryState } = props;
      const selectValue = item.value as string;
      !queryState[key] ? (queryState[key] = []) : null;
      const keyOptions = queryState[key];
      if (keyOptions.includes(selectValue)) {
        const index = keyOptions.indexOf(selectValue);
        keyOptions?.splice(index, 1);
      } else {
        keyOptions?.push(selectValue);
      }
      emit('pageRefresh');
    };

    // 生成筛选项
    const CustomAttrBox = () => {
      const { attrKey, queryState, searchConfigData } = props;
      const ItemArray: VueNode[] = [];
      const targetResult = find(searchConfigData, ['attr_key', attrKey]);
      if (!targetResult) {
        return null;
      }
      const { mapping } = targetResult;
      mapping.map((mapItem) => {
        const isActive = includes(queryState[targetResult.attr_key] || [], mapItem.value);
        if (targetResult.show_type === SearchSettingTypeEnum.IMAGE) {
          ItemArray.push(
            <li
              class={['box-img-item', { active: isActive }]}
              onClick={() => {
                multipleClick(mapItem, targetResult.attr_key);
              }}
            >
              <img src={mapItem.text} alt='' />
            </li>
          );
        } else {
          ItemArray.push(
            <li
              class={['box-item text-sm', { active: isActive }]}
              onClick={() => {
                multipleClick(mapItem, targetResult.attr_key);
              }}
            >
              <span>{mapItem.text}</span>
            </li>
          );
        }
      });
      return <ul class={'box-list flex flex-wrap'}>{ItemArray}</ul>;
    };

    return () => (
      <div class={'deck-list-filter-container'}>
        {props.attrKey ? (
          <div class={'py-md'}>
            <CustomAttrBox />
          </div>
        ) : null}
      </div>
    );
  },
});
